package com.ddstation.prescription_violate.controller;

import java.text.SimpleDateFormat;
import java.util.*;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ddstation.common.service.DataDictionaryService;
import com.ddstation.common.util.CheckUtil;
import com.ddstation.crm.menu.entity.DtInvsManageInstitutionMenuEntity;
import com.ddstation.crm.menu.service.MenuService;
import com.ddstation.exam.entity.DtHealthManageInstitutionGroupEntity;
import com.ddstation.exchange.service.DtHealthManageInstitutionGroupService;
import com.ddstation.master.entity.MaDataDictionaryEntity;
import com.ddstation.prescription_violate.model.InstitutionViolateResModel;
import com.ddstation.prescription_violate.model.ViolateDetailResModel;
import com.ddstation.util.getDateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ddstation.common.model.InvsCheckCommonSchParModel;
import com.ddstation.common.service.ViolationMessageService;
import com.ddstation.common.util.DateUtil;
import com.ddstation.crm.batchoutput.enmu.ExcelCellDataType;
import com.ddstation.crm.batchoutput.service.ExcelUtils;
import com.ddstation.crm.login.bean.SessionLoginData;
import com.ddstation.crm.outpatient.model.OutpatientModel;
import com.ddstation.crud.entity.DtInvsViolationManageEntity;
import com.ddstation.crud.entity.MaInvsViolationMessageEntity;
import com.ddstation.prescription_violate.model.ViolateDetailParaModel;
import com.ddstation.prescription_violate.service.PrescriptionViolateService;
import com.ddstation.sewage.service.SewageService;

@Controller @Lazy
public class PrescriptionViolateController {
	
	// 页面初始化
	@RequestMapping(value = "invs_prescription_violate.do")
	public String prescriptionViolateEvent(
			@RequestParam(required=false)Integer today, // 0：今日  1：本周
			@RequestParam(required=false)Integer status, // 9:全部 0正常 -1异常
			@RequestParam(required=false)String townId, // 地区ID
			@RequestParam(required=false)String otherData, // 其他参数
			Model model, HttpSession session) {

		// 从session获取基础数据
		SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY);
		if (loginData == null || loginData.getDoctor() == null || loginData.getInstitution() == null) {
			return "forward:login?timeout=true"; // session 过期
		}

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        // 获取当天
        Calendar cale = Calendar.getInstance();
		String lastday = format.format(cale.getTime());
		//取开始时间
        String firstday = getDateUtil.getFirstday(today);

		model.addAttribute("dtFrom", firstday); 	// 开始时间
		model.addAttribute("dtTo", lastday); 		// 当天
		model.addAttribute("status", status);// 状态
		model.addAttribute("townId", townId);// 地区ID

		if (otherData != null) {//存在其他参数则分割拼接参数
			String[] dataList = otherData.split(";");
			for(String dataInfo:dataList){
				if(dataInfo != null){
					String[] keyValue = dataInfo.split(":");
					if(keyValue.length == 2){
						model.addAttribute(keyValue[0], keyValue[1]);
					}
				}
			}
		}

		List<MaInvsViolationMessageEntity> violationMessageList = violationMessageService.selectList();
		if ( violationMessageList == null || violationMessageList.size()==0 ){
			throw new RuntimeException("master表【ma_invs_violation_message】没有数据！");
		}
		model.addAttribute("violationMessageList", violationMessageList);
		
		model.addAttribute("type", 2);

		//一级医疗机构类别
		List<MaDataDictionaryEntity> typeFirstList = dataDictionaryService.getCodeList("institution_type_first");

		model.addAttribute("typeFirstList", typeFirstList);

		//获取二级菜单目录
		String firstMenuUrl = "invs_prescription_violate.do";
//		List<DtInvsManageInstitutionMenuEntity> secondMenus = menuService.getSecondMenus(loginData.getJurisdictionMenus(), firstMenuUrl);
		List<DtInvsManageInstitutionMenuEntity> secondMenus = menuService.getSecondMenus(loginData.getWorkbenchMenus(), firstMenuUrl);
		model.addAttribute("secondMenus", secondMenus);

		return "pc/prescription_violate/prescription_violate";
	}
	
	/**
	 * 数据查询接口
	 * 
	 * @return
	 */
	@RequestMapping(value="invs_prescription_violate.do/load", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> loadPrescriptionViolateListEvent(
			@RequestParam String dtFrom,
			@RequestParam String dtTo,
			@RequestParam String registryStatus,
			@RequestParam String institutionTypeFirst,
			@RequestParam(required=false)String institutionName,
			@RequestParam(required=false) String townId,
			@RequestParam(required=false) String msgId,
            @RequestParam(required=false) Integer onlyShowAppeal,
			HttpSession session){
		SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY );
		
		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("errcode", -1);
		ret.put("errMsg", "系统出错，请稍后再试！");
		InvsCheckCommonSchParModel _p = new InvsCheckCommonSchParModel();
		_p.setInvsInstitutionId(loginData.getInstitution().getId());//卫监机构id
		_p.setInstitutionName(institutionName);
//		ret.put("todayList", prescriptionViolateService.searchRealTimeMonitor(_p));
		// 医疗机构别汇总
		_p.setDtFrom(dtFrom);
		_p.setDtTo(dtTo);
		_p.setCheckSt(Integer.parseInt(registryStatus));
		_p.setBusinessSubType(401);
		_p.setTownId(townId);
		_p.setMsgId(msgId);
		_p.setInstitutionTypeFirst(institutionTypeFirst);
        _p.setOnlyShowAppeal(onlyShowAppeal);
		List<InstitutionViolateResModel> institutionViolateResModelsRes=prescriptionViolateService.searchViolateCntGroupbyInstitutionId(_p);
		//查询全部父子机构信息
		Map<String, String> groupRelationship = getGroupRelationship();
		//汇总
		InstitutionViolateResModel institutionViolateAll = new InstitutionViolateResModel();
		int allMedicalCnt = 0;//病例总数
		int allPrescriptionCnt = 0;//处方总数
		int allViolateCnt = 0;//违规总数
		//定义重新组合集合
		List<InstitutionViolateResModel> comList=new ArrayList<>();
		Map<String, InstitutionViolateResModel> comMap = new HashMap<>();
		for(InstitutionViolateResModel institutionViolateResModel:institutionViolateResModelsRes){
			//如果传入消息为空就查询全部
			List<String> msgIds=new ArrayList<>();
			if(!CheckUtil.isEmpty(institutionViolateResModel.getMsgId())){
				String [] msgIdArray=institutionViolateResModel.getMsgId().split(",");
				for(String msg :msgIdArray){
					msgIds.add(msg);
				}
			}
			if(CheckUtil.isEmpty(msgId)||(!CheckUtil.isEmpty(msgId)&&msgIds.size()>0&&msgIds.contains(msgId))){
				if(Integer.parseInt(registryStatus)==institutionViolateResModel.getCheckSt()||Integer.parseInt(registryStatus)==9) {
					//汇总累计
					allMedicalCnt += institutionViolateResModel.getMedicalCnt();
					allPrescriptionCnt += institutionViolateResModel.getPrescriptionCnt();
					allViolateCnt += institutionViolateResModel.getViolateCnt();
					//判断是否为子机构
					String belongId = groupRelationship.get(institutionViolateResModel.getInstitutionId());
					//父ID不存在则判断自己为父ID
					if(belongId == null){
						belongId = institutionViolateResModel.getInstitutionId();
					}else{
						//存在父ID剔除名称及机构ID
						institutionViolateResModel.setInstitutionName(null);
						institutionViolateResModel.setInstitutionId(null);
					}
					//获取当前ID数据
					InstitutionViolateResModel belongInstitutionViolateRes = comMap.get(belongId);
					if(belongInstitutionViolateRes == null){
						//数据不存在则添加数据
						comMap.put(belongId,institutionViolateResModel);
					}else{
						//数据存在累加数据
						int violateCnt = belongInstitutionViolateRes.getViolateCnt() + institutionViolateResModel.getViolateCnt();
						int prescriptionCnt = belongInstitutionViolateRes.getPrescriptionCnt() + institutionViolateResModel.getPrescriptionCnt();
						int medicalCnt = belongInstitutionViolateRes.getMedicalCnt() + institutionViolateResModel.getMedicalCnt();
						belongInstitutionViolateRes.setViolateCnt(violateCnt);
						belongInstitutionViolateRes.setPrescriptionCnt(prescriptionCnt);
						belongInstitutionViolateRes.setMedicalCnt(medicalCnt);
						//替换名称为父ID对应名称
						if(institutionViolateResModel.getInstitutionName() != null){
							belongInstitutionViolateRes.setInstitutionName(institutionViolateResModel.getInstitutionName());
						}
						//替换机构ID为父ID对应机构ID
						if(institutionViolateResModel.getInstitutionId() != null){
							belongInstitutionViolateRes.setInstitutionId(institutionViolateResModel.getInstitutionId());
						}
						//存在一个状态为异常，则替换为异常
						if(institutionViolateResModel.getCheckSt() != 0){
							belongInstitutionViolateRes.setCheckSt(-1);
						}
						//保存新累加的对象
						comMap.put(belongId,belongInstitutionViolateRes);
					}
				}
			}
		}

		//遍历添加数据
		for (Map.Entry<String, InstitutionViolateResModel> entry : comMap.entrySet()) {
			//仅添加存在父机构数据
			if(entry.getValue() != null && entry.getValue().getInstitutionId() != null && entry.getValue().getInstitutionName() != null){
				comList.add(entry.getValue());
			}else{
				//扣除相关数量
				allMedicalCnt -= entry.getValue().getMedicalCnt();
				allPrescriptionCnt -= entry.getValue().getPrescriptionCnt();
				allViolateCnt -= entry.getValue().getViolateCnt();
			}
		}

		comList.sort((x, y) -> Double.compare(y.getViolateCnt(), x.getViolateCnt()));

		//保存总统计
		institutionViolateAll.setInstitutionName("总机构数：" + comList.size());
		institutionViolateAll.setMedicalCnt(allMedicalCnt);
		institutionViolateAll.setPrescriptionCnt(allPrescriptionCnt);
		institutionViolateAll.setViolateCnt(allViolateCnt);
		comList.add(0,institutionViolateAll);

		ret.put("violateCntList", comList);
        
		ret.put("errcode", 0);
		ret.put("errMsg", "");
		return ret;
	}

	//获取整理好的父子关系对照数据
	public Map<String,String> getGroupRelationship(){
		Map<String, String> map = new HashMap<>();
		List<DtHealthManageInstitutionGroupEntity> groupList = dtHealthManageInstitutionGroupService.selectAll();
		//遍历数据将子机构ID作为key，父机构ID作为value
		for(DtHealthManageInstitutionGroupEntity group:groupList){
			map.put(group.getChildInstitutionId(),group.getParentInstitutionId());
		}
		return map;
	}
	
	/**
	 * 数据查询接口 单个医疗机构
	 * 
	 * @return
	 */
	@RequestMapping(value="invs_prescription_violate.do/load_detail", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> loadPrescriptionViolateListEvent(
			@RequestBody ViolateDetailParaModel _in,
			HttpSession session){
		
		SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY );
		
		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("errcode", -1);
		ret.put("errMsg", "系统出错，请稍后再试！");

		// 访问权限check(防止异常调用)
		if ( !sewageService.checkAccessAuthority(loginData.getInstitution().getId(),_in.getInstitutionId()) ){
			ret.put("errMsg", "没有访问权限！");
			return ret;
		}
		
		// 日期check
		if ( StringUtils.isBlank(_in.getDtFrom()) 
				&& StringUtils.isBlank(_in.getDtTo()) 
				&& StringUtils.isBlank(_in.getDateYm())){
			ret.put("errMsg", "没有输入查询日期！");
			return ret;
		} 
		
		// 查询年月进来的情况【即综合查询页面调用时】
        if ( StringUtils.isNotBlank(_in.getDateYm())   ){
			String[] beginEndDate = DateUtil.getBeginEndDate(_in.getDateYm());
			if ( beginEndDate == null ){
				ret.put("errMsg", "系统出错，传入参数：年月错误！");
				return ret;
			}
			_in.setDtFrom(beginEndDate[0]);
			_in.setDtTo(beginEndDate[1]);
		}
		
        _in.setBusinessSubType(401);//固定查询处方违规信息
		//查询机构全部子ID
		DtHealthManageInstitutionGroupEntity entity = new DtHealthManageInstitutionGroupEntity();
		entity.setParentInstitutionId(_in.getInstitutionId());
		List<DtHealthManageInstitutionGroupEntity> dtHealthManageInstitutionGroupList = dtHealthManageInstitutionGroupService.select(entity);
		//设置机构ID集合，必定存在父机构ID
		List<String> institutionIdList = new ArrayList<>();
		institutionIdList.add(_in.getInstitutionId());
		if(dtHealthManageInstitutionGroupList != null && dtHealthManageInstitutionGroupList.size() > 0){
			//存在子ID则全部加入in条件查询
			for(DtHealthManageInstitutionGroupEntity dtHealthManageInstitutionGroup:dtHealthManageInstitutionGroupList){
				institutionIdList.add(dtHealthManageInstitutionGroup.getChildInstitutionId());
			}
		}
		_in.setInstitutionIdList(institutionIdList);
		//去除原机构ID条件
		_in.setInstitutionId(null);
		List<ViolateDetailResModel> datalist = prescriptionViolateService.searchDataList(_in);
		//替换展示 机构/科室 名称
		for(ViolateDetailResModel data:datalist){
			if(institutionIdList.get(0).equals(data.getInstitutionId())){
				data.setInstitutionShortName(data.getInstitutionName());
			}
		}

		ret.put("datalist", datalist);
        
		ret.put("errcode", 0);
		ret.put("errMsg", "");
		return ret;
	}
	
	/**
	 * 数据更新  跟进情况
	 * 
	 * @return
	 */
	@RequestMapping(value="invs_prescription_violate.do/update", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> updateFollowStatus(
			@RequestParam Integer violateId,
			@RequestParam String institutionId,
			HttpSession session){
		
		SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY );
		
		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("errcode", -1);
		ret.put("errMsg", "系统出错，请稍后再试！");

		// 访问权限check(防止异常调用)
		if ( !sewageService.checkAccessAuthority(loginData.getInstitution().getId(),institutionId) ){
			ret.put("errMsg", "没有访问权限！");
			return ret;
		}
		DtInvsViolationManageEntity w = new DtInvsViolationManageEntity();
		w.setFollowStatus(1);
		w.setFollowerId(loginData.getDoctor().getSupervisorId());
		w.setFollowTm(new Date());
		w.setId(violateId.toString());
		prescriptionViolateService.updateFollowStatus(w);
        
		ret.put("errcode", 0);
		ret.put("errMsg", "");
		return ret;
	}
	
	/**
	 * 数据查询接口[处方]
	 * 
	 * @return
	 */
	@RequestMapping(value="invs_prescription_violate.do/show_prescription", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> loadPrescriptionViolatePrescriptionEvent(
			@RequestParam String violateId,//dt_invs_violation_manage.id
			@RequestParam String institutionId,//机构ID
			HttpSession session){
		
		SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY );
		
		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("errcode", -1);
		ret.put("errMsg", "系统出错，请稍后再试！");
	
		// 访问权限check(防止异常调用)
		if ( !sewageService.checkAccessAuthority(loginData.getInstitution().getId(),institutionId) ){
			ret.put("errMsg", "没有访问权限！");
			return ret;
		}

		OutpatientModel outpatient = prescriptionViolateService.serachOutpatient(violateId);
		ret.put("outpatient",outpatient );
		
		ret.put("errcode", 0);
		ret.put("errMsg", "");
		return ret;
	}
	
	
	/**
	 * 导出
	 * 
	 * @return 
	 */
	@RequestMapping(value="invs_prescription_violate.do/output", method = RequestMethod.POST)
	public void prescriptionViolateDetailEvent(
			@RequestParam String startDt,
			@RequestParam String endDt,
			HttpSession session,
			HttpServletRequest request,
			HttpServletResponse response) {
		
		// excel生成用数组生成
		SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY );
		String invsInstitutionId = loginData.getInstitution().getId();
		// excel生成，并弹出下载文件提示
		String fileNamePrefix = "处方违规"+startDt+"至"+endDt;
		String[] titles = {"违规内容","医疗机构名","时间"};
		// 显示指定其中几列为金额类型
		ExcelCellDataType[] cellDataType = new ExcelCellDataType[3];
		cellDataType[0] = ExcelCellDataType.TEXT;
		cellDataType[1] = ExcelCellDataType.TEXT;
		cellDataType[2] = ExcelCellDataType.TEXT;
		excelUtil.setCellDataType(cellDataType);
		
		List<String[]> list = prescriptionViolateService.getExcelData(invsInstitutionId,startDt,endDt);
		excelUtil.exportExcel( fileNamePrefix , titles,list, response);
	}

	@Inject private MenuService menuService;
	@Inject	private ExcelUtils excelUtil;
	@Inject private SewageService sewageService;
	@Inject private PrescriptionViolateService prescriptionViolateService; 
	@Inject private ViolationMessageService violationMessageService;
	@Inject private DtHealthManageInstitutionGroupService dtHealthManageInstitutionGroupService;
	@Inject private DataDictionaryService dataDictionaryService;

}
